﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TagRequester
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public Http.Request Request;
        public Http.Response Response;


        public ViewModel.RequestViewModel requestViewModel;


        public MainWindow()
        {
            InitializeComponent();

            // 初始化数据
            this.Request = new Http.Request();
            this.Response = new Http.Response();

            this.requestViewModel = new ViewModel.RequestViewModel() {
                Url = "http://onlytg.com/Tools/HttpRequestInfo",
                Cookie = ""
            };


            // 添加绑定
            this.grpRequest.DataContext = requestViewModel;
        }

        /// <summary>
        /// 窗体启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExitApp(object sender, RoutedEventArgs e)
        {
            this.Close();
        }


        private void ShowMessage(string msg)
        {
            this.txtStatus.Text = string.Format("status:{0} [{1}]", msg, DateTime.Now.ToShortTimeString());
        }



        /// <summary>
        /// Get请求
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Get(object sender, RoutedEventArgs e)
        {
            this.requestViewModel.isPost = false;
            CreateRequest();
            GetResponse();
            ShowResult();
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Post(object sender, RoutedEventArgs e)
        {
            this.requestViewModel.isPost = true;
            CreateRequest();
            GetResponse();
            ShowResult();
        }




        /// <summary>
        /// 创建一个Http请求
        /// </summary>
        void CreateRequest()
        {
            var req = new Http.Request();

            req.Url = requestViewModel.Url;
            req.Cookie = requestViewModel.Cookie;

            #region 设置请求头 , 匹配 第一次出现的 :或者=  左边的为name，右边的为value      
            var headers = this.requestViewModel.Headers.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string line in headers)
            {
                Match m = Regex.Match(line, "^(.+?)[:=](.*)$");
                // 没有匹配就代表输入不对,限制输入格式
                if (!m.Success)
                    continue;
                string name = m.Groups[1].Value;
                string value = m.Groups[2].Value;
                //以下case出来的，都是受限制的标头，不能被更改 参见http://msdn.microsoft.com/zh-cn/library/system.net.webheadercollection(v=vs.100).aspx
                switch (name.ToLower())
                {
                    case "accept":
                        req.Accept = value;
                        break;
                    case "connection":
                        req.Connection = value;
                        break;
                    case "content-length":
                        break;
                    case "content-type":
                        break;
                    case "date":
                        break;
                    case "expect":
                        break;
                    case "host":
                        break;
                    case "if-modified-since":
                        break;
                    case "range":
                        break;
                    case "referer":
                        req.Referer = value;
                        break;
                    case "transfer-encoding":
                        break;
                    case "user-agent":
                        req.UserAgent = value;
                        break;
                    case "proxy-connection":
                        break;
                    case "x-requested-with":
                        if (value == "XMLHttpRequest")
                        {
                            req.Headers.Add(name, value);
                            req.ProtocolVersion = HttpVersion.Version10;
                        }
                        break;
                    default:
                        req.Headers.Add(name, value);
                        break;
                }
            }
            #endregion

            #region 如果是post，就设置post参数
            if (requestViewModel.isPost)
            {
                req.Method = Http.HttpMethod.POST;

                var strPostdata = this.requestViewModel.FormData.Replace(':', '=');
                var postdata = strPostdata.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);



                //当只有一行的时候，可能输入的已经拼凑好的参数 ie=utf-8&kw=u2nn 这样
                if (postdata.Length == 1)
                {
                    req.PostData = postdata[0];
                }
                else
                {
                    // 非一行的时候，0行在这里循环不了无所谓，多行的话，必然是键值模式
                    foreach (string line in postdata)
                    {
                        if (string.IsNullOrEmpty(line))
                            continue;
                        Match m = Regex.Match(line, "^(.+?)[=](.*)$");
                        // 没有匹配就代表输入不对
                        if (!m.Success)
                            continue;
                        string name = m.Groups[1].Value;
                        string value = m.Groups[2].Value;
                        req.PostParameters.Add(name, value);
                    }
                }
            }
            #endregion


            this.Request = req;
        }

        void GetResponse()
        {
            this.Response = this.Request.GetResponse();
        }

        void ShowResult()
        {
            // 显示Response's Headers
            var query = from key in this.Response.Headers.AllKeys select key + ":" + this.Response.Headers[key];
            this.txtResponseHeaders.Text = string.Join("\r\n", query.ToArray<string>());
            // 显示Response's Content
            this.txtResponseContent.Text = this.Response.Content;
        }





        /// <summary>
        /// Copy Response's Content
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CopyContent(object sender, RoutedEventArgs e)
        {
            // 只有返回内容非空才Copy
            if (!string.IsNullOrEmpty(this.txtResponseContent.Text))
            {
                Clipboard.SetText(this.txtResponseContent.Text);
                ShowMessage("Has been copied");
            }
        }

        /// <summary>
        /// 查找返回内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FindResponseContent(object sender, RoutedEventArgs e)
        {
            var strFind = this.txtFind.Text;


            do
            {
                // 首先文本框均不能为空
                if (string.IsNullOrEmpty(strFind))
                {
                    break;
                }

                if (string.IsNullOrEmpty(this.txtResponseContent.Text))
                {
                    break;
                }

                // 可以进行多次查找
                var index = txtResponseContent.Text.IndexOf(strFind, txtResponseContent.SelectionStart);
                if (index > -1)
                {
                    txtResponseContent.SelectionStart = index;
                    txtResponseContent.SelectionLength = strFind.Length;
                    txtResponseContent.ScrollToHome();
                    ShowMessage(string.Format("在位置{0}上找到", index));
                }
                else
                {
                    ShowMessage("没有找到");
                }


            } while (false);
        }

        private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            Console.Write(this.requestViewModel.Url);
        }
    }


}
